import React, { useEffect, useState, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { io, Socket } from "socket.io-client";

interface Category {
  label: string;
  icon: string;
}

const SERVER_URL = ""; // 连接到同源地址，让Vite代理处理

const categories: Category[] = [
  { label: "听歌房", icon: "🎵" },
  { label: "音乐房", icon: "🎤" },
  { label: "娱乐房", icon: "👍" },
  { label: "交友房", icon: "💖" },
];

const RoomList = () => {
  const [rooms, setRooms] = useState<string[]>([]);
  const [inputRoom, setInputRoom] = useState<string>("");
  const [showModal, setShowModal] = useState<boolean>(false);
  const [modalRoomName, setModalRoomName] = useState<string>("");
  const navigate = useNavigate();
  const socketRef = useRef<Socket | null>(null);

  useEffect(() => {
    const socket: Socket = io(SERVER_URL, {
      path: "/socket.io/",
      transports: ['websocket', 'polling']
    });
    socketRef.current = socket;
    
    socket.emit("get-rooms");
    socket.on("rooms", (roomList: string[]) => {
      setRooms(roomList);
    });
    socket.on("room-created", (room: string) => {
      setRooms((prev) => [...prev, room]);
    });
    
    return () => {
      socket.disconnect();
    };
  }, []);

  const handleCreateRoom = () => {
    setShowModal(true);
    setModalRoomName("");
  };

  const handleModalConfirm = () => {
    if (modalRoomName.trim()) {
      socketRef.current?.emit("create-room", modalRoomName.trim());
      navigate(`/voiceroom?room=${encodeURIComponent(modalRoomName.trim())}`);
      setShowModal(false);
      setModalRoomName("");
    }
  };

  const handleJoinRoom = (room: string) => {
    navigate(`/voiceroom?room=${encodeURIComponent(room)}`);
  };

  return (
    <div style={{ 
      minHeight: "100vh", 
      background: "#181828", 
      color: "#fff", 
      boxSizing: "border-box", 
      maxWidth: 600, 
      margin: "0 auto", 
      paddingBottom: 24 
    }}>
      {/* 顶部分类和搜索 */}
      <div style={{ padding: "24px 12px 0 12px" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div style={{ fontSize: 22, fontWeight: 700 }}>蒙面派对</div>
          <button
            style={{
              background: "#282846",
              color: "#fff",
              border: 0,
              borderRadius: 16,
              padding: "6px 16px",
              fontSize: 16
            }}
            onClick={handleCreateRoom}
          >
            创建房间
          </button>
        </div>
        {/* 横向滚动分类栏 */}
        <div style={{ overflowX: "auto", margin: "18px 0 8px 0" }}>
          <div style={{ display: "flex", gap: 12, whiteSpace: "nowrap" }}>
            {categories.map(c => (
              <div key={c.label} style={{
                background: "#23233a",
                borderRadius: 16,
                padding: "10px 18px",
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
                fontSize: 15,
                minWidth: 64,
                flex: "0 0 auto"
              }}>
                <span style={{ fontSize: 24 }}>{c.icon}</span>
                <span style={{ marginTop: 4 }}>{c.label}</span>
              </div>
            ))}
          </div>
        </div>
        <div style={{ margin: "12px 0" }}>
          <input
            value={inputRoom}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => setInputRoom(e.target.value)}
            placeholder="输入房间号/搜索"
            style={{ 
              width: "100%", 
              borderRadius: 18, 
              border: 0, 
              padding: "10px 16px", 
              background: "#23233a", 
              color: "#fff", 
              fontSize: 15, 
              boxSizing: "border-box" 
            }}
          />
        </div>
      </div>
      {/* 房间卡片列表 */}
      <div style={{ padding: "0 12px" }}>
        {rooms.length === 0 && (
          <div style={{ color: "#aaa", marginTop: 32, textAlign: "center" }}>
            暂无房间
          </div>
        )}
        {rooms.map(room => (
          <div 
            key={room} 
            style={{ 
              background: "linear-gradient(90deg,#3a2b6c,#23233a)", 
              borderRadius: 20, 
              margin: "16px 0", 
              padding: "18px 18px 14px 18px", 
              boxShadow: "0 2px 12px #0002", 
              display: "flex", 
              alignItems: "center", 
              justifyContent: "space-between", 
              maxWidth: "100%", 
              overflow: "hidden" 
            }}
          >
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 18, fontWeight: 600, wordBreak: "break-all" }}>
                {room}
              </div>
              <div style={{ fontSize: 13, color: "#bdbdf7", marginTop: 4 }}>
                语音房间
              </div>
            </div>
            <button 
              onClick={() => handleJoinRoom(room)} 
              style={{ 
                background: "#6c63ff", 
                color: "#fff", 
                border: 0, 
                borderRadius: 16, 
                padding: "8px 18px", 
                fontSize: 15, 
                flexShrink: 0 
              }}
            >
              进入
            </button>
          </div>
        ))}
      </div>
      {/* 创建房间弹窗 */}
      {showModal && (
        <div style={{
          position: "fixed", 
          left: 0, 
          top: 0, 
          width: "100vw", 
          height: "100vh", 
          background: "rgba(0,0,0,0.45)", 
          zIndex: 9999,
          display: "flex", 
          alignItems: "center", 
          justifyContent: "center"
        }}>
          <div style={{ 
            background: "#23233a", 
            borderRadius: 16, 
            padding: 28, 
            minWidth: 260, 
            boxShadow: "0 4px 24px #0006", 
            display: "flex", 
            flexDirection: "column", 
            alignItems: "center" 
          }}>
            <div style={{ fontSize: 18, fontWeight: 600, marginBottom: 18 }}>
              创建房间
            </div>
            <input
              value={modalRoomName}
              onChange={(e: React.ChangeEvent<HTMLInputElement>) => setModalRoomName(e.target.value)}
              placeholder="请输入房间名"
              style={{ 
                borderRadius: 12, 
                border: 0, 
                padding: "8px 14px", 
                background: "#181828", 
                color: "#fff", 
                fontSize: 15, 
                marginBottom: 18, 
                width: 180 
              }}
              autoFocus
            />
            <div style={{ display: "flex", gap: 16 }}>
              <button 
                onClick={() => setShowModal(false)} 
                style={{ 
                  background: "#444", 
                  color: "#fff", 
                  border: 0, 
                  borderRadius: 10, 
                  padding: "7px 18px", 
                  fontSize: 15 
                }}
              >
                取消
              </button>
              <button 
                onClick={handleModalConfirm} 
                style={{ 
                  background: "#6c63ff", 
                  color: "#fff", 
                  border: 0, 
                  borderRadius: 10, 
                  padding: "7px 18px", 
                  fontSize: 15 
                }}
              >
                确认
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default RoomList;